<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #container {
        width: 1350px;
        height: 900px;
      }

      #root {
        display: flex;
        width: 100%;
      }

      #root > div:first-child {
        width: 200px;
        margin-right: 10px;
        padding: 5px;
        box-shadow: 2px 2px 2px 2px #333;
      }
      #root > div:first-child {
        display: flex;
        flex-direction: column;
      }

      .context_menu {
        position: relative;
        min-width: 12rem;
        padding: 0;
        background-color: white;
      }

      .context_menu p {
        cursor: pointer;
        padding: 0.25rem 1.25rem;
      }

      .context_menu p:hover {
        background: #ccc;
      }

      .btn {
        width: 80px;
        margin-top: 10px;
      }

      .marker-route {
        width: 15px;
        height: 15px;
        background-color: #22ddb8;
        border-radius: 10px;
      }
      .active {
        background-color: #f76809;
      }
      .content {
        background-color: rgba(0, 0, 0, 0.3);
        padding: 1px;
        color: white;
        display: flex;
        align-items: center;
      }
      .content span {
        display: block;
        width: 20px;
        height: 20px;
        background-color: #3366bb;
        margin: 0 10px;
      }
      .content p {
        margin-right: 10px;
      }

      .test {
        height: 30px;
        box-sizing: content-box;
        padding: 2px 10px;
        line-height: 30px;
        display: inline;
        float: left;
      }
      .test a {
        color: #333 !important;
      }
      .test span {
        width: 80px !important;
        margin-left: 10px;
        border-radius: 10px;
      }
      .amap-info-content {
        background-color: rgba(255, 255, 255, 0.6);
      }
      .test_container {
        background-color: rgba(255, 255, 255, 0.6);
        display: flex;
        width: 180px;
        flex-direction: column;
        padding: 10px 18px 10px 10px;
        line-height: 1.4;
        overflow: auto;
        justify-content: center;
        align-items: center;
        border: 1px solid rgba(0, 0, 0, 0.2);
      }
      .input_inner {
        margin-right: 5px;
        border: 1px solid #333;
        border-radius: 2px;
        width: 30px;
      }
    </style>
  </head>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: "29ee4c1b8e3949fa7b10dcb2f0f4d4dc",
    };
  </script>
  <script
    type="text/javascript"
    src="https://webapi.amap.com/maps?v=2.0&key=b59c490f61a694b9d7576dd864f74d6e&plugin=AMap.Scale,AMap.ToolBar,AMap.MouseTool,AMap.DistrictSearch,AMap.Geocoder"
  ></script>
  <script type="text/javascript" src="./index.js"></script>
  <script src="https://webapi.amap.com/loca?key=b59c490f61a694b9d7576dd864f74d6e&v=2.0.0"></script>
  <body>
    <div id="root">
      <div>
        <h3>添加选点请输入坐标</h3>
        <label>
          经度：
          <input />
        </label>
        <label>
          纬度：
          <input />
        </label>
        <button class="btn">输入完成</button>
        <button class="btn">清空输入</button>
      </div>
      <div id="container"></div>
    </div>
  </body>
  <script src="https://webapi.amap.com/loader.js"></script>
  <script type="text/javascript">
    var headColors = ["#3366bb", "#6622FF"];
    // 存储当前选中点 DOM
    var currentPonit = "";
    // 当前选重点信息
    var currentData = {};
    // 工具方法
    // 修改DOM 类名
    function changeStyle(res, data) {
      if (currentPonit !== "") {
        currentPonit.classList.remove("active");
      }
      currentPonit = res.children[0];
      currentData = data;
      currentPonit.classList.add("active");
    }
    // 清除点信息
    function clearPoint() {
      if (currentPonit) {
        currentPonit.classList.remove("active");
      }
      currentPonit = "";
      currentData = {};
    }
    // 设置线信息
    function setLines(lnglat, color, weight) {
      return new AMap.Polyline({
        path: lnglat,
        // showDir:true ,// 设置线方向
        strokeColor: color, // 线颜色
        strokeWeight: weight, // 线宽
        strokeOpacity: 0.6, // 透明度
      });
    }

    // 输入事件
    const done = document.getElementsByClassName("btn")[0];
    const del = document.getElementsByClassName("btn")[1];
    const longitude = document.getElementsByTagName("input")[0]; // 经度
    const latitude = document.getElementsByTagName("input")[1]; // 纬度
    done.addEventListener("click", () => {
      console.log(longitude.value);
      // 中国经纬度范围， 经度 73.33 - 135.05 , 纬度 3.51-53.33
      const lng = longitude.value;
      const lat = latitude.value;
      if (Number.isNaN(Number(lng)) || Number.isNaN(Number(lat))) {
        alert("请输入数值");
        return;
      }
      if (lng <= 73 || lng > 135) {
        alert("请输入正确的经度");
        return;
      }
      if (lat < 3.5 || lat > 53) {
        alert("请输入正确的纬度");
        return;
      }
      const marker = {
        position: [lng, lat],
        name: "新增点位",
        pointData: {
          out: 0,
          provide: 0,
        },
      };
      setMarker(marker);
      clearInput();
    });
    del.addEventListener("click", clearInput);
    // 清除输入框
    function clearInput() {
      longitude.value = "";
      latitude.value = "";
    }

    function setInput(e, name) {
      let text =
        e.target.parentElement.parentElement.children[0].innerText.split(
          "供给点"
        )[0];
      let current = coordData.filter((item) => {
        return item.name === text;
      });
      window.localStorage.setItem(text + name, e.target.value);
    }

    // 信息窗体
    var infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(0, -10),
      retainWhenClose: true,
    });
    infoWindow.on("open", function (...arg) {
      let inputOut = document.getElementById("inputOut");
      let inputPro = document.getElementById("inputPro");
      inputOut.addEventListener("change", (e) => {
        setInput(e, "inputOut");
        window.location.reload();
      });
      inputPro.addEventListener("change", (e) => {
        setInput(e, "inputPro");
        window.location.reload();
      });
    });

    function markerClick(e) {
      infoWindow.setContent(e.target.contents);
      infoWindow.open(map, e.target.getPosition());
    }

    // 抽离点位信息设置
    function setMarker(marker) {
      //创建右键菜单
      var contextMenu = new AMap.ContextMenu();
      //右键放大
      contextMenu.addItem(
        "放大一级",
        function () {
          map.zoomIn();
        },
        0
      );
      //右键缩小
      contextMenu.addItem(
        "缩小一级",
        function () {
          map.zoomOut();
        },
        1
      );
      contextMenu.addItem("设置起点", function () {
        console.log(marker, markerd.dom);
        changeStyle(markerd.dom, marker);
        contextMenu.close(); // 关闭右键菜单
      });
      contextMenu.addItem("与起点连线", function () {
        if (!currentPonit) {
          alert("请选择起点");
          contextMenu.close();
          return;
        } else {
          // 这里其实可以根据数据判定线类型了，因为第二个选中点的信息+和第一个选中点的信息都有了,但是过滤方法会比较复杂
          let path = [currentData.position, marker.position];
          const polyline1 = setLines(path, "#3366bb", 5);
          map.add([polyline1]);
          clearPoint();
        }
        contextMenu.close(); // 关闭右键菜单
      });
      let content = '<div class="marker-route"></div>';
      var markerd = new AMap.Marker({
        map: map,
        // icon: marker?.icon,
        content,
        offset: new AMap.Pixel(-8, -8),
        visible: true, // 点标记是否可见
        position: [marker.position[0], marker.position[1]],
      });
      //根据坐标获取行政区域
      const lnglat = markerd.getPosition();
      let geocoder = new AMap.Geocoder({
        city: "全国",
      });
      geocoder.getAddress(lnglat, (status, result) => {
        console.log("status,result", status, result);
      });
      let inputO = window.localStorage.getItem(marker.name + "inputOut");
      let inputP = window.localStorage.getItem(marker.name + "inputPro");
      console.log(inputO, inputP);
      markerd.contents = `
    <div>${marker.name}供给点</div>
    <div>出口压力：<input id="inputOut" class="input_inner" value="${
      inputO ?? marker?.pointData?.out
    }"/>kPa</div>
    <div>供给量：<input id="inputPro" class="input_inner" value="${
      inputP ?? marker?.pointData?.provide
    }" />m³</div>
    <div>位置：经度${marker.position[0]},纬度${marker.position[1]}</div>`;

      markerd.data = marker;
      markerd.on("click", markerClick);
      if (marker.name === "新疆") {
        // 触发上面的点击事件
        markerd.emit("click", { target: markerd });
      }
      //绑定鼠标右击事件——弹出右键菜单
      markerd.on("rightclick", function (e) {
        contextMenu.open(map, e.lnglat);
      });
    }

    // 上来就显示的中心点  北京 116.397, 39.918
    var lnglat = new AMap.LngLat(105, 38);

    // 地图初始化
    var map = new AMap.Map("container", {
      zoom: 4.8,
      center: lnglat,
      // mapStyle: 'amap://styles/blue', //设置地图的显示样式
    });

    map.clearMap(); // 清除地图覆盖物
    // 地图是否可拖拽和缩放
    map.setStatus({
      dragEnable: true, // 是否可拖拽
      zoomEnable: true, // 是否可缩放
    });

    var markers = [
      {
        // 可以配置 icon 替换点标记的图标, 可以使用在线的 也可以使用本地的
        // icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-2.png',
        position: [116.368904, 39.913423],
      },
    ];
    // 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照
    coordData.forEach(function (marker) {
      setMarker(marker);
    });

    //创建右键菜单
    var menu = new ContextMenu(map);

    //自定义菜单类
    function ContextMenu(map) {
      var me = this;

      //地图中添加鼠标工具MouseTool插件
      this.mouseTool = new AMap.MouseTool(map);

      this.contextMenuPositon = null;
      var content = [];
      content.push("<div class='info context_menu'>");
      content.push("  <p onclick='menu.delMarkerMenu()'>移除上次选中信息</p>");
      content.push("</div>");
      //通过content自定义右键菜单内容
      this.contextMenu = new AMap.ContextMenu({
        isCustom: true,
        content: content.join(""),
      });

      //地图绑定鼠标右击事件——弹出右键菜单
      map.on("rightclick", function (e) {
        me.contextMenu.open(map, e.lnglat);
        me.contextMenuPositon = e.lnglat; //右键菜单位置
      });
    }

    ContextMenu.prototype.delMarkerMenu = function () {
      // 右键菜单上次选中点的信息
      clearPoint();
      this.mouseTool.close();
      this.contextMenu.close();
    };

    // menu.contextMenu.open(map, lnglat);  初始化就会显示右键菜单

    // 过滤线方法
    function setLine(arr) {
      return arr.reduce((prev, item) => {
        if (item?.line) {
          prev.push(...item.line);
        }
        return prev;
      }, []);
    }
    let renderLine = setLine(coordData);

    // 设置线
    let polyline = renderLine.reduce((prev, item, index) => {
      let weight = item.type === 1 ? 5 : 3;
      let color = item.type === 1 ? headColors[0] : headColors[1];
      prev.push(setLines(item.current, color, weight));
      return prev;
    }, []);

    /* // 通过信息窗体 实现 图例
  const content = `<div class="content"><span></span><p>区域管道</p></div>`
  // 创建 infoWindow 实例
  const infoWindow = new AMap.InfoWindow({
    isCustom:true ,// 使用自定义窗体
    content,
    offset: new AMap.Pixel(0,0)
  })
  // 在指定位置打开已创建的信息窗体
  let position = new AMap.LngLat(126, 25);
  infoWindow.open(map, position); */

    var loca = new Loca.Container({
      map,
    });
    window._loca = loca;

    // 图例, 图例可以实例化多个，使用定位来设置位置
    var lengend = new Loca.Legend({
      loca: loca,
      title: {
        label: "管道类型",
        fontColor: "rgba(255,255,255,1)",
        fontSize: "16px",
      },
      style: {
        backgroundColor: "rgba(255,255,255,0.2)",
        left: "20px",
        bottom: "40px",
        fontSize: "12px",
      },
      dataMap: [
        { label: "省级管道", color: headColors[1] },
        { label: "县级管道", color: headColors[0] },
      ],
    });

    //修改图例排列方式
    document
      .getElementsByClassName("amap-loca loca-controls")[0]
      .setAttribute("id", "testid");
    var lis = document.querySelectorAll("#testid li");
    for (var i = 0; i < lis.length; i++) {
      console.log(lis[i]);
      lis[i].setAttribute("class", "test");
    }

    // 测试点位
    let testP = new AMap.Marker({
      map: map,
      content: `<a class="amap-info-close" id="testP_btn">×</a><div class="test_container"><div>西宁至乌鲁木齐管段</div>
    <div>管径：159 mm</div><div>壁厚：8.2 mm</div><div>管内径：142.6 mm</div>
    <div>流量：5 m³/h</div><div>起点压强：100 kPa</div><div>终点压强：86.2 kPa</div>
    <div>流向：乌鲁木齐至西宁</div></div>`,
      position: [93, 46],
    });
    document.getElementById("testP_btn").addEventListener("click", () => {
      map.remove(map.getAllOverlays("marker")[0]);
    });

    map.add([...polyline, testP]);
  </script>
</html>
